<?php

class UploadController extends ExtendedController
{
    private $maxSize = 1048576;
    private $regex = "/^.*\.(jpg|jpeg|png|gif)$/i";
    private $uploadDir = '../public/uploads';
    
    function __construct()
    {
        parent::__construct();
    }
    
    public function index($nof = 1)
    {
        $this->loadView('upload_form');
        $data = array('numberOfFile' => $nof);
        $this->views['upload_form']->setBlockData($data);
        $this->views['upload_form']->setBlock('v-menu',null);
        $this->views['upload_form']->render();
    }
    
    public function submit()
    {
        global $application_dir;      
        $this->loadModel('files');
        if(isset($_POST['submit']))
        {
            $this->loadView('upload_form');
            $data = array('numberOfFile' => 1);
            $fileArray = $_FILES['file'];
            $nof = count($fileArray['name']);
            for($i = 0; $i < $nof; $i++)
            {
                if($fileArray['name'][$i] == NULL)
                    continue;
                if(!preg_match($this->regex, $fileArray['name'][$i]))
                {
                    Utility::error('<strong>Có lỗi !!!! Bạn chỉ có thể upload file ảnh</strong>', 'upload');
                    exit();
                }
                $path = pathinfo($fileArray['name'][$i]);
                if($fileArray['size'][$i] > $this->maxSize)
                {
                    Utility::error("<strong>Có lỗi !!!! File bạn thao tác có kích cỡ vượt quá quy định là" . ($this->maxSize / 1024) . " KB</strong>", 'upload');
                    exit();
                }
                if($fileArray['error'][$i] > 0)
                {
                    Utility::error("<strong>Có lỗi xảy ra , file không thể upload : <br /> " . $fileArray['error'][$i], 'upload');
                    exit();
                }
                $imageInfo = getimagesize($fileArray['tmp_name'][$i]);
                $filename = date('Ydm') . '_' . microtime(TRUE);
                $fileLocation = $this->uploadDir . DS . $filename . "." . $path['extension'];
                $fileUrl = '/public/uploads/' . $filename . "." . $path['extension'];
                if(move_uploaded_file($fileArray['tmp_name'][$i], $fileLocation))
                {
                    $data['uploadedFiles'][] = $fileUrl;
                }                
            }
            $this->views['upload_form']->setBlockData($data);        
            $this->views['upload_form']->render();
        }
        else
        {
            $this->index();
        }
    }
}

?>
